package pers.xiaojun.boot.module.system.service.oauth2;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import pers.xiaojun.boot.common.exception.BusinessException;
import pers.xiaojun.boot.module.system.constants.OAuth2ClientConstants;
import pers.xiaojun.boot.module.system.dao.mapper.oauth2.OAuth2ClientMapper;
import pers.xiaojun.boot.module.system.dao.entity.oauth2.OAuth2ClientDO;

import java.util.List;

import static pers.xiaojun.boot.module.system.constants.BusinessCodeConstants.*;

/**
 * OAuth 2.0 客户端服务层实现类
 *
 * @author xiaojun
 * @since 2025-10-16
 */
@Service
public class OAuth2ClientServiceImpl extends ServiceImpl<OAuth2ClientMapper, OAuth2ClientDO> implements OAuth2ClientService {

    @Override
    public OAuth2ClientDO checkOAuth2Client(String clientId, String secret, String responseType, String redirectUri, List<String> scopes) {
        OAuth2ClientDO client = this.baseMapper.selectOne(new LambdaQueryWrapper<OAuth2ClientDO>()
                .eq(OAuth2ClientDO::getClientId, clientId)
        );
        // 校验客户端ID
        if (client == null) {
            throw new BusinessException(OAUTH2_CLIENT_NOT_EXISTS);
        }
        // 默认客户端无需校验其他内容
        if (StrUtil.equals(clientId, OAuth2ClientConstants.DEFAULT_CLIENT)) {
            return client;
        }
        // 校验密钥
        if (StrUtil.isNotEmpty(secret) && !StrUtil.equals(secret, client.getSecret())) {
            throw new BusinessException(OAUTH2_SECRET_NOT_MATCH);
        }
        // 校验授权空间
        if (scopes != null && !CollUtil.containsAll(client.getScopes(), scopes)) {
            throw new BusinessException(OAUTH2_SCOPES_INVALID);
        }
        // 校验授权方式
        if (StrUtil.isNotEmpty(responseType) &&!CollUtil.contains(client.getAuthorizedGrantTypes(), responseType)) {
            throw new BusinessException(OAUTH2_AUTHORIZED_GRANT_TYPE_INVALID);
        }
        // 校验重定向地址
        if (StrUtil.isNotEmpty(redirectUri) && !CollUtil.contains(client.getRedirectUris(), redirectUri)) {
            throw new BusinessException(OAUTH2_REDIRECT_URI_INVALID);
        }
        return client;
    }

    @Override
    public OAuth2ClientDO checkOAuth2Client(String clientId, String secret) {
        return checkOAuth2Client(clientId, secret, null, null, null);
    }
}
